<template>
  <teleport to="body">
    <div class="modern-floating-assistant" :class="{ visible: isVisible }">
      <!-- 现代化触发按钮 -->
      <div class="assistant-trigger" @click="toggleAssistant">
        <div class="trigger-icon">
          <i class="fas fa-wand-magic-sparkles"></i>
        </div>
        <div class="trigger-ripple"></div>
      </div>

      <!-- 现代化面板 -->
      <transition name="assistant-panel">
        <div v-show="expanded" class="assistant-panel">
          <div class="panel-header">
            <div class="header-content">
              <div class="header-icon">
                <i class="fas fa-sparkles"></i>
              </div>
              <h4>写作助手</h4>
            </div>
            <button class="close-btn" @click="toggleAssistant">
              <i class="fas fa-times"></i>
            </button>
          </div>

          <div class="panel-content">
            <!-- 格式化工具 -->
            <div class="tool-section">
              <div class="section-header">
                <div class="section-icon">
                  <i class="fas fa-text-height"></i>
                </div>
                <h5>格式化</h5>
              </div>
              <div class="action-grid">
                <button class="action-btn" title="加粗" @click="formatText('bold')">
                  <i class="fas fa-bold"></i>
                </button>
                <button class="action-btn" title="斜体" @click="formatText('italic')">
                  <i class="fas fa-italic"></i>
                </button>
                <button class="action-btn" title="标题" @click="formatText('heading')">
                  <i class="fas fa-heading"></i>
                </button>
                <button class="action-btn" title="引用" @click="formatText('quote')">
                  <i class="fas fa-quote-right"></i>
                </button>
              </div>
            </div>

            <!-- 插入工具 -->
            <div class="tool-section">
              <div class="section-header">
                <div class="section-icon">
                  <i class="fas fa-plus"></i>
                </div>
                <h5>插入</h5>
              </div>
              <div class="action-grid">
                <button class="action-btn" title="链接" @click="insertContent('link')">
                  <i class="fas fa-link"></i>
                </button>
                <button class="action-btn" title="图片" @click="insertContent('image')">
                  <i class="fas fa-image"></i>
                </button>
                <button class="action-btn" title="代码" @click="insertContent('code')">
                  <i class="fas fa-code"></i>
                </button>
                <button class="action-btn" title="表格" @click="insertContent('table')">
                  <i class="fas fa-table"></i>
                </button>
              </div>
            </div>

            <!-- AI助手 -->
            <div class="tool-section ai-section">
              <div class="section-header">
                <div class="section-icon ai-icon">
                  <i class="fas fa-robot"></i>
                </div>
                <h5>AI 助手</h5>
                <div class="ai-badge">
                  <span>Pro</span>
                </div>
              </div>
              <div class="ai-grid">
                <button class="ai-btn" @click="aiAssist('continue')">
                  <i class="fas fa-pen"></i>
                  续写
                </button>
                <button class="ai-btn" @click="aiAssist('optimize')">
                  <i class="fas fa-circle-check"></i>
                  优化
                </button>
                <button class="ai-btn" @click="aiAssist('summary')">
                  <i class="fas fa-list"></i>
                  摘要
                </button>
                <button class="ai-btn" @click="aiAssist('title')">
                  <i class="fas fa-heading"></i>
                  标题
                </button>
              </div>
            </div>

            <!-- 快捷键 -->
            <div class="tool-section shortcuts-section">
              <div class="section-header">
                <div class="section-icon">
                  <i class="fas fa-keyboard"></i>
                </div>
                <h5>快捷键</h5>
              </div>
              <div class="shortcut-list">
                <div class="shortcut-item">
                  <div class="shortcut-keys">
                    <kbd>Ctrl</kbd>
                    <span>+</span>
                    <kbd>S</kbd>
                  </div>
                  <span class="shortcut-desc">保存</span>
                </div>
                <div class="shortcut-item">
                  <div class="shortcut-keys">
                    <kbd>Ctrl</kbd>
                    <span>+</span>
                    <kbd>B</kbd>
                  </div>
                  <span class="shortcut-desc">加粗</span>
                </div>
                <div class="shortcut-item">
                  <div class="shortcut-keys">
                    <kbd>Ctrl</kbd>
                    <span>+</span>
                    <kbd>I</kbd>
                  </div>
                  <span class="shortcut-desc">斜体</span>
                </div>
                <div class="shortcut-item">
                  <div class="shortcut-keys">
                    <kbd>Ctrl</kbd>
                    <span>+</span>
                    <kbd>K</kbd>
                  </div>
                  <span class="shortcut-desc">链接</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </teleport>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
// Font Awesome icons will be used directly in template

interface EditorAPI {
  focus?: () => void;
  handle?: (command: string, value?: any) => void;
  insertText?: (text: string) => void;
  $el?: {
    querySelector?: (selector: string) => HTMLTextAreaElement | null;
  };
}

interface Props {
  editorRef?: EditorAPI | null;
  editorType?: 'markdown' | 'rich';
}

const props = withDefaults(defineProps<Props>(), { editorType: 'markdown' });

const isVisible = ref(false);
const expanded = ref(false);

// 检测鼠标位置，自动显示助手
const checkMousePosition = (e: MouseEvent) => {
  const { clientX, clientY } = e;
  const { innerWidth, innerHeight } = window;

  // 鼠标在右侧边缘时显示
  if (clientX > innerWidth - 100) {
    isVisible.value = true;
  } else {
    isVisible.value = false;
    expanded.value = false;
  }
};

const toggleAssistant = () => {
  console.log('Floating assistant clicked, expanded:', expanded.value);
  expanded.value = !expanded.value;
};

// 格式化文本
const formatText = (type: string) => {
  if (!props.editorRef) return;

  try {
    switch (type) {
      case 'bold':
        if (props.editorType === 'markdown') {
          insertMarkdown('**粗体文本**');
        } else {
          // 使用WangEditor的API
          props.editorRef?.focus();
          props.editorRef?.handle?.('bold', '');
        }
        break;
      case 'italic':
        if (props.editorType === 'markdown') {
          insertMarkdown('*斜体文本*');
        } else {
          // 使用WangEditor的API
          props.editorRef?.focus();
          props.editorRef?.handle?.('italic', '');
        }
        break;
      case 'heading':
        if (props.editorType === 'markdown') {
          insertMarkdown('\n## 标题\n');
        } else {
          // 使用WangEditor的API
          props.editorRef?.focus();
          props.editorRef?.handle?.('header', '2');
        }
        break;
      case 'quote':
        if (props.editorType === 'markdown') {
          insertMarkdown('\n> 引用文本\n');
        } else {
          // 使用WangEditor的API
          props.editorRef?.focus();
          props.editorRef?.handle?.('blockquote', '');
        }
        break;
    }
    ElMessage.success('格式已应用');
  } catch (error) {
    ElMessage.error('格式化失败');
  }
};

// 插入内容
const insertContent = (type: string) => {
  if (!props.editorRef) return;

  try {
    switch (type) {
      case 'link':
        if (props.editorType === 'markdown') {
          insertMarkdown('[链接文本](https://example.com)');
        } else {
          // 在富文本编辑器中插入链接
          const url = prompt('请输入链接地址：', 'https://example.com');
          if (url) {
            const text = prompt('请输入链接文本：', '链接文本');
            if (text) {
              // 使用WangEditor的API
              props.editorRef?.focus();
              props.editorRef?.insertText?.(text);
              props.editorRef?.handle?.('link', { href: url, text });
            }
          }
        }
        break;
      case 'image':
        if (props.editorType === 'markdown') {
          insertMarkdown('![图片描述](图片地址)');
        } else {
          // 触发图片上传
          props.editorRef?.focus();
          props.editorRef?.handle?.('insertImage', null);
        }
        break;
      case 'code':
        if (props.editorType === 'markdown') {
          insertMarkdown('```\n// 代码\n```');
        } else {
          // 使用WangEditor的API
          props.editorRef?.focus();
          props.editorRef?.handle?.('code', '');
        }
        break;
      case 'table':
        if (props.editorType === 'markdown') {
          insertMarkdown('| 列1 | 列2 |\n|-----|-----|\n| 内容 | 内容 |');
        } else {
          ElMessage.info('请在工具栏中插入表格');
        }
        break;
    }
    ElMessage.success('内容已插入');
  } catch (error) {
    ElMessage.error('插入失败');
  }
};

// 插入Markdown文本
const insertMarkdown = (text: string) => {
  const textarea = props.editorRef?.$el?.querySelector('textarea');
  if (textarea) {
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const value = textarea.value;

    textarea.value = value.substring(0, start) + text + value.substring(end);
    textarea.selectionStart = textarea.selectionEnd = start + text.length;

    // 触发input事件
    textarea.dispatchEvent(new Event('input'));
  }
};

// AI助手功能
const aiAssist = async (type: string) => {
  ElMessage.info('AI助手功能开发中...');
  // 这里可以接入AI API
  switch (type) {
    case 'continue':
      ElMessage.info('AI正在续写...');
      break;
    case 'optimize':
      ElMessage.info('AI正在优化表达...');
      break;
    case 'summary':
      ElMessage.info('AI正在生成摘要...');
      break;
    case 'title':
      ElMessage.info('AI正在建议标题...');
      break;
  }
};

// 生命周期
onMounted(() => {
  document.addEventListener('mousemove', checkMousePosition);
});

onUnmounted(() => {
  document.removeEventListener('mousemove', checkMousePosition);
});
</script>

<style scoped lang="scss">
.modern-floating-assistant {
  position: fixed;
  right: 24px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 9998;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: auto;

  &.visible {
    opacity: 1;
  }

  &:not(.visible) {
    opacity: 0;
    pointer-events: none;
  }

  // 现代化触发按钮
  .assistant-trigger {
    width: 48px;
    height: 48px;
    background: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border: 1px solid rgba(0, 0, 0, 0.08);
    position: relative;
    overflow: hidden;

    &:hover {
      transform: translateY(-2px) scale(1.05);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
      background: #f8f9fa;
    }

    &:active {
      transform: translateY(0) scale(0.98);
    }

    .trigger-icon {
      width: 24px;
      height: 24px;
      color: #5f6368;
      transition: all 0.2s ease;
      z-index: 2;
      position: relative;
    }

    &:hover .trigger-icon {
      color: #1967d2;
      transform: rotate(15deg);
    }

    .trigger-ripple {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 100%;
      height: 100%;
      background: radial-gradient(circle, rgba(25, 103, 210, 0.1) 0%, transparent 70%);
      transform: translate(-50%, -50%) scale(0);
      border-radius: 50%;
      transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
    }

    &:hover .trigger-ripple {
      transform: translate(-50%, -50%) scale(1.5);
    }
  }

  // 现代化面板
  .assistant-panel {
    position: absolute;
    right: 64px;
    top: 50%;
    transform: translateY(-50%);
    width: 360px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
    overflow: hidden;
    border: 1px solid rgba(0, 0, 0, 0.08);
    backdrop-filter: blur(20px);

    .panel-header {
      padding: 20px 24px;
      background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
      border-bottom: 1px solid rgba(0, 0, 0, 0.06);
      display: flex;
      align-items: center;
      justify-content: space-between;

      .header-content {
        display: flex;
        align-items: center;
        gap: 12px;

        .header-icon {
          width: 32px;
          height: 32px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
        }

        h4 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #202124;
        }
      }

      .close-btn {
        width: 28px;
        height: 28px;
        border: none;
        background: transparent;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: #5f6368;
        transition: all 0.2s ease;

        &:hover {
          background: rgba(0, 0, 0, 0.05);
          color: #202124;
        }
      }
    }

    .panel-content {
      padding: 8px;
      max-height: 70vh;
      overflow-y: auto;

      .tool-section {
        margin-bottom: 16px;
        background: #fafbfc;
        border-radius: 12px;
        padding: 16px;
        border: 1px solid rgba(0, 0, 0, 0.04);
        transition: all 0.2s ease;

        &:hover {
          background: #f8f9fa;
          border-color: rgba(0, 0, 0, 0.08);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }

        &:last-child {
          margin-bottom: 0;
        }

        .section-header {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 16px;

          .section-icon {
            width: 28px;
            height: 28px;
            background: white;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #5f6368;
            border: 1px solid rgba(0, 0, 0, 0.08);

            &.ai-icon {
              background: linear-gradient(135deg, #fbbc04 0%, #f29900 100%);
              color: white;
              border: none;
            }
          }

          h5 {
            margin: 0;
            font-size: 13px;
            font-weight: 600;
            color: #202124;
          }

          .ai-badge {
            margin-left: auto;
            background: linear-gradient(135deg, #fbbc04 0%, #f29900 100%);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
          }
        }

        .action-grid,
        .ai-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 8px;

          .action-btn,
          .ai-btn {
            width: 100%;
            aspect-ratio: 1;
            border: none;
            background: white;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #5f6368;
            font-size: 10px;
            font-weight: 500;
            gap: 4px;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            border: 1px solid rgba(0, 0, 0, 0.08);

            &:hover {
              background: #f1f3f4;
              color: #202124;
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            &:active {
              transform: translateY(0);
            }

            svg {
              width: 16px;
              height: 16px;
            }
          }

          .ai-btn {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            color: #5f6368;
            border: 1px solid rgba(251, 188, 4, 0.2);

            &:hover {
              background: linear-gradient(135deg, #fef7e0 0%, #f8f9fa 100%);
              color: #f29900;
              border-color: rgba(251, 188, 4, 0.4);
            }
          }
        }

        .shortcut-list {
          .shortcut-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.04);

            &:last-child {
              border-bottom: none;
              padding-bottom: 0;
            }

            .shortcut-keys {
              display: flex;
              align-items: center;
              gap: 4px;

              kbd {
                background: white;
                border: 1px solid rgba(0, 0, 0, 0.12);
                border-radius: 4px;
                padding: 4px 8px;
                font-size: 11px;
                font-family: 'SF Mono', Monaco, monospace;
                color: #5f6368;
                font-weight: 500;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
              }

              span {
                color: #9aa0a6;
                font-size: 10px;
                font-weight: 500;
              }
            }

            .shortcut-desc {
              font-size: 12px;
              color: #5f6368;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

// 动画
.assistant-panel-enter-active,
.assistant-panel-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: top right;
}

.assistant-panel-enter-from {
  opacity: 0;
  transform: translateY(-50%) scale(0.9) translateX(20px);
}

.assistant-panel-leave-to {
  opacity: 0;
  transform: translateY(-50%) scale(0.9) translateX(20px);
}

// 滚动条样式
:deep(.panel-content)::-webkit-scrollbar {
  width: 6px;
}

:deep(.panel-content)::-webkit-scrollbar-track {
  background: transparent;
}

:deep(.panel-content)::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  transition: background 0.2s ease;
}

:deep(.panel-content)::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}
</style>
